/*
 *
 *  Copyright (C) 2010 GSyC/LibreSoft, Universidad Rey Juan Carlos.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Raúl Román López <rroman@gsyc.es>
 *
 */

package com.LibreGeoSocial.App.Content;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.LibreGeoSocial.Api.Audio;
import com.LibreGeoSocial.Api.GeoNode;
import com.LibreGeoSocial.Api.LibreGeoSocial;
import com.LibreGeoSocial.Api.Note;
import com.LibreGeoSocial.Api.Photo;
import com.LibreGeoSocial.App.R;

public class ContentUpload{

	public static final int ACTIVITY_PICK_GALLERY = 10000;
	
	public static final int MENU = 10000;
	public static final int MENU_NOTE = 10001;
	public static final int MENU_PHOTO = 10002;
	public static final int MENU_AUDIO = 10003;
	
	public static final int DIALOG_UPLOAD = 10000;
	public static final int DIALOG_PBAR = 10001;
	
	private Activity mActivity;
	
	private GeoNode resource;
	private Location resource_location;
	private String path;
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			if(mActivity.isFinishing())
				return;
			
			if (msg.what == 0){
        		Toast.makeText(mActivity, 
     					   "Resource added correctly!",
     					   Toast.LENGTH_SHORT).show();
        	}else{
        		Toast.makeText(mActivity, 
        				"Error while the status was setted: " + 
        				LibreGeoSocial.getInstance().getLastMsgServer(), 
        				Toast.LENGTH_LONG).show();
        	}
			mActivity.removeDialog(DIALOG_PBAR);
		}
	};
	
	public ContentUpload(Activity mActivity){
		this.mActivity = mActivity;
	}
	
	public void setResourceLocation(Location resource_location){
		this.resource_location = resource_location;
	}
	
	public void onCreateOptionsMenu(Menu menu){
		SubMenu sub = menu.addSubMenu(0, MENU, 0, "Upload content")
			.setIcon(R.drawable.up);
		sub.add(0,MENU_NOTE, 0, "Note");
		sub.add(0,MENU_PHOTO, 0, "Photo");
		sub.add(0,MENU_AUDIO, 0, "Audio");
	}
	
	public boolean onOptionsItemSelected (MenuItem item){
		switch(item.getItemId()){
		case MENU_NOTE:
			resource = new Note (null, "", "",
					  resource_location.getLatitude(),
					  resource_location.getLongitude(),
					  resource_location.getAltitude(),
					  null, null);
			mActivity.showDialog(DIALOG_UPLOAD);
			break;
			
		case MENU_PHOTO:
			resource = new Photo(0, 
					resource_location.getLatitude(),
					resource_location.getLongitude(), 
					resource_location.getAltitude(), 
					0.0, "", "", "", null, null);
			
			Intent i = new Intent(Intent.ACTION_PICK) ;
	    	i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
	    					 MediaStore.Images.Media.CONTENT_TYPE) ;
	    	
	    	mActivity.startActivityForResult(i,ACTIVITY_PICK_GALLERY) ;
			break;
			
		case MENU_AUDIO:
			resource = new Audio  (null, 
					  "", 
					  "",
					  "", "",
					  resource_location.getLatitude(),
					  resource_location.getLongitude(),
					  resource_location.getAltitude(),
					  null, null);
			Intent i2;
			if(Build.VERSION.SDK_INT < Build.VERSION_CODES.ECLAIR){
				i2 = new Intent(Intent.ACTION_PICK) ;
				i2.setDataAndType(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
									MediaStore.Audio.Media.CONTENT_TYPE) ;
			}else{
				i2 = new Intent(mActivity, ContentPick.class) ;
				i2.putExtra("MAIN_PATH", "/sdcard/audio_lgs/");
				i2.putExtra("MIME_TYPE", "audio/3gpp");
			}
	    	
	    	mActivity.startActivityForResult(i2,ACTIVITY_PICK_GALLERY) ;
			break;
			
		default:
			return false;
		}
		return true;
	}
	
	public Dialog onCreateDialog(int id){
		
		switch(id){
		case DIALOG_UPLOAD:
			
			LayoutInflater factory = LayoutInflater.from(mActivity);
    		final View textEntryView = factory.inflate(R.layout.note, null);
    		
    		final EditText title = (EditText) textEntryView.findViewById (R.id.txtTitle);
    		final EditText body = (EditText) textEntryView.findViewById (R.id.txtBody);
    		
    		final Spinner spinner = (Spinner)textEntryView.findViewById(R.id.spinner_privacy);
    		final Spinner spinner_location = (Spinner)textEntryView.findViewById(R.id.spinner_location_privacy);
    		
    		final String[] privacy_types = mActivity.getResources().getStringArray(R.array.privacy);
            
            ArrayAdapter<CharSequence> adapter =  new ArrayAdapter<CharSequence>(mActivity, android.R.layout.simple_spinner_dropdown_item);
            for(int i = 0; i<privacy_types.length; i++){
            	adapter.add(privacy_types[i]);
            }
            
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            
            ArrayAdapter<CharSequence> adapter_location =  new ArrayAdapter<CharSequence>(mActivity, android.R.layout.simple_spinner_dropdown_item);
            for(int i = 0; i<privacy_types.length; i++){
            	adapter_location.add(privacy_types[i]);
            }
            
            adapter_location.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            
            spinner.setAdapter(adapter);
            spinner_location.setAdapter(adapter_location);
            
            
	        return new AlertDialog.Builder(mActivity)	        
	        .setTitle("Upload resource")
	        .setView(textEntryView)
	        .setPositiveButton("Upload", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            	
	                /* User clicked OK so do some stuff */ 
	            	mActivity.showDialog(DIALOG_PBAR);
	            	new Thread(){
	            		public void run(){
	            			boolean result = false;
	    	            	if(Note.class.isInstance(resource)){
	    	            		Note note = (Note) resource;
	    	            		note.setTitle(title.getText().toString());
	    	            		note.setBody(body.getText().toString());
	    	            		
	    	            		result = LibreGeoSocial.getInstance().createNote(note);
	    	            	}else if(Photo.class.isInstance(resource)){
	    	            		Photo photo = (Photo) resource;
	    	            		photo.setName(title.getText().toString());
	    	            		photo.setDescription(body.getText().toString());
	    	            		photo.setUrl(path);
	    	            		
	    	            		result = LibreGeoSocial.getInstance().uploadPhoto(photo);
	    	            	}else if(Audio.class.isInstance(resource)){
	    	            		Audio audio = (Audio) resource;
	    	            		audio.setName(title.getText().toString());
	    	            		audio.setDescription(body.getText().toString());
	    	            		audio.setPath(path);
	    	            		
	    	            		result = LibreGeoSocial.getInstance().uploadAudio(audio);
	    	            	}
	    	            	if(result){
	    	            		int id = LibreGeoSocial.getInstance().getLastId();
	    	            		result = LibreGeoSocial.getInstance().setPrivacyNode(id, 
	    	            				mActivity.getResources().getStringArray(R.array.values_privacy)[spinner.getSelectedItemPosition()], 
	    	            				false);
	    	            		if(result)
	    	            			result = LibreGeoSocial.getInstance().setPrivacyNode(id, 
		    	            				mActivity.getResources().getStringArray(R.array.values_privacy)[spinner_location.getSelectedItemPosition()], 
		    	            				true);
	    	            	}
	    	            	
	    	            	if(result)
	    	            		mHandler.sendEmptyMessage(0);
	    	            	else
	    	            		mHandler.sendEmptyMessage(-1);
	            		}
	            	}.start();
	            }
	        })
	        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	
	                /* User clicked cancel so do some stuff */
	            }
	        })
	        .create();
	        
		case DIALOG_PBAR:
    		ProgressDialog dialog = new ProgressDialog(mActivity);
    		dialog.setMessage("Uploading...");
    		dialog.setIndeterminate(true);
    		dialog.setCancelable(true);
    		return dialog;
			
		}
		return null;
		
	}
	
	public boolean onActivityResult(int requestCode, int resultCode, Intent data){
		if(resultCode != Activity.RESULT_OK)
			return false;
		
		switch(requestCode){
		
		case ACTIVITY_PICK_GALLERY:
			if((Build.VERSION.SDK_INT < Build.VERSION_CODES.ECLAIR) || (!Audio.class.isInstance(resource))){
				Cursor c = mActivity.managedQuery(data.getData(),null,null,null,null);
				if( c.moveToFirst() )
					path = c.getString(1) ;
			}else{
				path = data.getStringExtra("PATH");
			}

			mActivity.showDialog(DIALOG_UPLOAD);
			break;
			
		default:
			return false;
		}
		return true;
	}
}